package com.study.controller;

import com.study.bean.entity.Dormitory;
import com.study.bean.entity.Student;
import com.study.bean.query.DormitoryQuery;
import com.study.service.impl.DormitoryServiceImpl;
import com.study.util.MyBeanUtils;
import com.study.util.PageInfo;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet("/dormitory/*")
public class DormitoryController extends BaseController{


    private final DormitoryServiceImpl dormitoryService = new DormitoryServiceImpl();

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String method = req.getParameter("method");

        switch (method){
            case "selectByPage":
                selectByPage(req, resp);
                break;
            case "addDormitory":
                addDormitory(req,resp);
                break;
            case "viewStu":
                viewStu(req,resp);
                break;
        }
    }

    private void viewStu(HttpServletRequest req, HttpServletResponse resp) {
        System.out.println("DormitoryController.viewStu");
        DormitoryQuery dormitoryQuery = MyBeanUtils.copyToBean(req, DormitoryQuery.class);
         List<Student> students = dormitoryService.viewStu(dormitoryQuery);
         if (students.isEmpty()){
             PageInfo pageInfo = new PageInfo(1, students);
             toJSON(resp, pageInfo);
         }else {
             PageInfo pageInfo = new PageInfo(0, students);
             toJSON(resp, pageInfo);
         }



    }


    private void addDormitory(HttpServletRequest req, HttpServletResponse resp) {
        System.out.println("DormitoryController.addDormitory");
        Dormitory dormitory = MyBeanUtils.copyToBean(req, Dormitory.class);
        Boolean b = dormitoryService.addDormitory(dormitory);
        if (b){
            PageInfo pageInfo = new PageInfo(0, b);
            toJSON(resp, pageInfo);
        }else {
            PageInfo pageInfo = new PageInfo(1, b);
            toJSON(resp, pageInfo);
        }
    }



    private void selectByPage(HttpServletRequest req, HttpServletResponse resp) {
        System.out.println("BlogServlet.selectByPage");
        /*String page = req.getParameter("page");
        String limit = req.getParameter("limit");
        String name = req.getParameter("name");
        BlogQuery blogQuery = new BlogQuery(Integer.parseInt(page), Integer.parseInt(limit), name);*/
        DormitoryQuery dormitoryQuery = MyBeanUtils.copyToBean(req, DormitoryQuery.class);
        System.out.println(dormitoryQuery);
        PageInfo pageInfo = dormitoryService.selectByPage(dormitoryQuery);

        //JSONUtils.toJSON(resp, pageInfo);
        toJSON(resp, pageInfo);
    }
}
